<?php
namespace app\index\controller;
use think\Request;
use think\Controller;
use think\facade\Session;
use think\Db;

class Login extends Controller
{
    public function index()
    {
        return $this->fetch('./login');
    }

    // 注册
    public function register(Request $request)
    {
        if($request->isPost()){
            $data['username'] = $request->param('username','','htmlspecialchars');
            $data['password'] = md5($request->param('password'));
            $data['des'] = $request->param('des');
            // 判断是否存在该用户
            $user = Db::name('user')->where(['username'=>$data['username'],'password'=>$data['password']])->field('id,username,avatar,login_time,login_num,des')->find();
            if($user){
                // 直接登录
                Session::set('user_info',['uid'=>$user['id'],'username'=>$user['username'],'avatar'=>$user['avatar'],'des'=>$user['des']]);
                Db::name('user')->where('id',$user['id'])->update(['login_time'=>time()]);
                Db::name('user')->where('id',$user['id'])->setInc('login_num');
                return json(['code'=>200,'msg'=>'登录成功']);
            } else {
                $like_user = Db::name('user')->where(['username'=>$data['username']])->field('id,username,avatar,login_time,login_num')->find();
                if($like_user){
                    return json(['code'=>400,'msg'=>'密码输入错误']);
                } else {
                    // 注册并登录
                    $data['login_time'] = time();
                    $data['login_num'] = 1;
                    $data['avatar'] = '/static/image/header/head_'.rand(1,20).'.jpg';
                    $res = Db::name('user')->insertGetId($data);
                    if($res){
                        // 登录
                        Session::set('user_info',['uid'=>$res,'username'=>$data['username'],'avatar'=>$data['avatar'],'des'=>$data['des']]);
                        return json(['code'=>200,'msg'=>'登录成功']);
                    } else {
                        return json(['code'=>400,'msg'=>'注册失败']);
                    }
                }
            }
        }
    }

    // 退出登录
    public function login_out()
    {
        Session::clear('user_info');
        return redirect('/login');
    }

}
